package web.controller;

import java.net.http.HttpRequest;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.View;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;
import org.springframework.web.servlet.view.RedirectView;

@Controller
public class IndexController {
    // @RequestMapping("/")
    // public ModelAndView indexByFirst() {
    // ModelAndView view = new ModelAndView("index");
    // return view;
    // }

    @RequestMapping(path = { "index", "/" })
    public RedirectView indexByAbsolute(HttpServletResponse res) {
        return new RedirectView("/web/");
    }

    // @RequestMapping("/web/${path}")
    // public ModelAndView indexByTemplate(HttpServletRequest req, Model model,
    // @Param("path") String path) {
    // System.out.println(model);
    // ModelAndView view = new ModelAndView("index");
    // // String path = req.getServletPath();
    // // view.addObject("target", path);
    // return view;
    // }

    /**
     * 以 <b>/web</b> 为根目录，避免匹配到静态资源
     *
     *
     * 规则
     *  1. / -> /web/
     *  2. /web/ -> /index
     *  3. /web/123 -> component/123.js | 404
     *  4. /web/123/ -> component/123/index.js | 404
    */
    @RequestMapping(path = { "/web/**/*", "/web/" })
    public Object index(HttpServletRequest request, ModelAndView model) {
        ModelAndView view = new ModelAndView("index");
        String path = request.getServletPath();

        if (path == null || path.equals("/")) {
            return view;
        }

        Integer index = path.indexOf("/web");

        if (index == -1 || index == null) {
            return view;
        }

        path = path.substring(index + "/web".length());

        if (path.charAt(path.length() - 1) == '/') {
            path = path + "index";
        }

        view.addObject("servlet_path", path);
        return view;
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}
